-module(worker).
-export([init/1, do_task/0]).

%%% DESIGN NOTE:        server code and worker code must comprise a single file respectively
%%% TODO:   os:cmd(Command) returns a string, must cast to appropriate type

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
init(Num_Of_Workers) when is_integer(Num_Of_Workers) ->
    erlang:set_cookie(node(), cookie),
    ok = worker_utils:spawn_workers(Num_Of_Workers),
    true.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
do_task() ->
	{ok, {Job_ID, Server}, {Task_ID, Task, File_Type}} = receive_info(task),
	ok = do_task(Job_ID, Server, {Task_ID, Task, File_Type}),
    do_task().
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
do_task(Job_ID, Server, {Task_ID, Task, File_Type}) ->
    case File_Type of
        java -> {Compile_Cmd, Execute_Cmd} = worker_utils:build_command(Job_ID, Task, javac);
        cpp  -> {Compile_Cmd, Execute_Cmd} = worker_utils:build_command(Job_ID, Task, 'g++');
        c    -> {Compile_Cmd, Execute_Cmd} = worker_utils:build_command(Job_ID, Task, gcc);
        erl  -> {Compile_Cmd, Execute_Cmd} = worker_utils:build_command(Job_ID, Task, erl);
        py   -> {Compile_Cmd, Execute_Cmd} = worker_utils:build_command(Job_ID, Task, python); %Compile_Cmd is just "echo" 
        _    -> cluster_utils:print("Invalid file type: ~p", [File_Type]), {Compile_Cmd, Execute_Cmd} = {"echo", "echo"}
    end,
    _        = worker_utils:execute_command(Compile_Cmd),
    Result   = worker_utils:execute_command(Execute_Cmd),
    cluster_utils:send_messages({Server, Job_ID}, [{result, Task_ID, Result}]),
    ok.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
